#include "sfc_cpu.h"
#include "sfc_famicom.h"

#include <assert.h>

static inline void sfc_load_prgrom_8k(sfc_famicom_t* famicom, int dst_bank_id, int src_bank_id) {
	famicom->prg_banks[(0x8000 >> 13) + dst_bank_id] = famicom->rom_info.data_prgrom + 8 * 1024 * src_bank_id;
}

static inline sfc_ecode sfc_load_mapper_00(sfc_famicom_t* famicom);

#define SFC_CASE_LOAD_MAPPER(id) case 0x##id: return sfc_load_mapper_##id(famicom);

extern sfc_ecode sfc_load_mapper(sfc_famicom_t* famicom, uint8_t id) {
	switch (id) {
	SFC_CASE_LOAD_MAPPER(00);
	}
	return SFC_MAPPER_NOT_FOUND;
}

// MAPER 000 - NROM
// https://wiki.nesdev.org/w/index.php?title=NROM

static sfc_ecode sfc_mapper_00_reset(sfc_famicom_t* famicom) {
	assert(famicom->rom_info.count_prgrom_16kb && "bad count");
	assert(famicom->rom_info.count_chrrom_8kb && "bad count");

	// NES 2.0 的 PRG-ROM 只能为 16KB 或 32KB
	// CPU $8000-$BFFF: First 16 KB of ROM.
	// CPU $C000-$FFFF: Last 16 KB of ROM (NROM-256) or mirror of $8000-$BFFF (NROM-128).
	const int id2 = famicom->rom_info.count_prgrom_16kb & 2;

	sfc_load_prgrom_8k(famicom, 0, 0);
	sfc_load_prgrom_8k(famicom, 1, 1);
	sfc_load_prgrom_8k(famicom, 2, id2 + 0);
	sfc_load_prgrom_8k(famicom, 3, id2 + 1);
	return SFC_ERROR_OK;
}

sfc_ecode sfc_load_mapper_00(sfc_famicom_t* famicom) {
	famicom->mapper.reset = sfc_mapper_00_reset;
	return SFC_ERROR_OK;
}
